package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.admin.mapper.LoginUserMapper;
import com.usian.admin.service.LoginUserService;
import com.usian.common.dtas.BaseServiceImpl;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class LoginUserServiceImpl extends BaseServiceImpl<LoginUserMapper, AdUser> implements LoginUserService {
    @Override
    public ResponseResult login(AdUserDto adUser) {
        //检查参数
        if (adUser==null|| StringUtils.isBlank(adUser.getPassword())||StringUtils.isBlank(adUser.getName()))
            return ErrorParam;
            //2.根据名称查找用户 是否存在
            AdUser user = getOne(new LambdaQueryWrapper<AdUser>().eq(AdUser::getName, adUser.getName()));
            if (user==null)return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户不存在");
            String password = user.getPassword(); //表里的密码
            //加盐后的密码跟表里的密码对比
            String paw= DigestUtils.md5DigestAsHex((adUser.getPassword()+user.getSalt()).getBytes());
            if (password.equals(paw)){
                Map<String, Object> hashMap = new HashMap<>();
                user.setPassword("");
                user.setSalt("");
                hashMap.put("token", AppJwtUtil.getToken(user.getId().longValue()));
                hashMap.put("user",user);
                return ResponseResult.okResult(hashMap);
            }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户或密码错误");
    }
}
